//
//  MonitorVC.m
//  UHealth
//
//  Created by gjtxz on 15/3/19.
//  Copyright (c) 2015年 gjtx. All rights reserved.
//

#import "MonitorVC.h"
#import "MonitorEditVC.h"
#import "MonitorInfoVC.h"

#import "MJRefresh.h"
#import "UIImageView+WebCache.h"

@interface MonitorVC ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong)UITableView         *conTableView;
@property (nonatomic,strong)NSMutableArray      *dataArr;

@property (nonatomic,strong)UIView              *noneView;

@end

@implementation MonitorVC

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.view.backgroundColor = kBacColor;
        self.navigationItem.title = kLocal(@"Monitor");
        
        self.title = kLocal(@"Monitor");
        self.tabBarItem.image = [UIImage imageNamed:@"my_blue"];
        self.tabBarItem.selectedImage = [UIImage imageNamed:@"my_grey"];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(btnClick:)];
    self.navigationItem.rightBarButtonItem.tag = 2;
    _dataArr = [NSMutableArray array];
    

    _noneView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - kNavHeight-kTabBarHeight)];
    _noneView.backgroundColor = kBacColor;
    
    // 添加监护人按钮
    UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    addBtn.frame = CGRectMake(0, 10, WIDTH, 44);
    addBtn.tag = 2;
    [addBtn setTitle:kLocal(@"add_monitor") forState:UIControlStateNormal];
    addBtn.backgroundColor = kBlueColor;
    [addBtn setImage:[UIImage imageNamed:@"add_index"] forState:UIControlStateNormal];
    [addBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    [_noneView addSubview:addBtn];
    
    // 监护人介绍按钮
    UIButton *infoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    infoBtn.frame = CGRectMake((WIDTH-200)/2, 150, 200, 44);
    infoBtn.tag = 3;
    infoBtn.backgroundColor = kBlueColor;
    [infoBtn setTitle:kLocal(@"what_is_monitor") forState:UIControlStateNormal];
    [infoBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    [_noneView addSubview:infoBtn];
    
    UILabel *infol = [[UILabel alloc]initWithFrame:CGRectMake(0, 200, WIDTH, 21)];
    infol.text = kLocal(@"auto_remind");
    infol.textAlignment = NSTextAlignmentCenter;
    infol.textColor = [UIColor grayColor];
    [_noneView addSubview:infol];

    _conTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-kNavHeight) style:UITableViewStyleGrouped];
    _conTableView.backgroundColor = kBacColor;
    _conTableView.dataSource = self;
    _conTableView.delegate = self;
    _conTableView.tableFooterView = [UIView new];
    _conTableView.tableHeaderView = _noneView;
    
    __unsafe_unretained typeof(self) vc = self;
    
    [_conTableView addHeaderWithCallback:^{
        
        if (!kNetID) {
            [[iToast makeText:kLocal(@"notLogin")] show];
            [vc.conTableView headerEndRefreshing];
            return ;
        }
        if (!kNetIsOK) {
            [[iToast makeText:kLocal(@"netNoOk")] show];
            [vc.conTableView headerEndRefreshing];
            return ;
        }
        //默认用户famid的网络数据
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        manager.requestSerializer.timeoutInterval = 5;
        manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject: @"text/html"];
        NSString *postStr = [NSString stringWithFormat:@"%@/action/json/guardian.jsp?",kBaseUrl];
        NSDictionary *parameters = @{@"action"      : @"getGuardianList",
                                     @"userid"      :[NSString stringWithFormat:@"%ld",(long)kNetID],
                                     @"mobile_type" :@"2",
                                     @"fromtype"    :@"1",
                                     @"app_line"    :kAPPLine};
        
        [manager POST:postStr parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
            kDebug(@"Success: %@", operation.responseString);
//          {"dataJson":[{"guardian_id":"15","mem_userid":"22120224","mem_name":"qqq","ismessage":"0","mem_headpic":"http://testapi.uwellnesshk.com/upload/201503/17/14-12-59_3977_100.png","data":{}},
            BOOL type = [[responseObject objectForKey:@"type"] boolValue];
            if(type){//成功
                vc.dataArr = responseObject[@"dataJson"];
            }else{
            }
            if(vc.dataArr.count <= 0){
                vc.conTableView.tableHeaderView = vc.noneView;
            }else{
                vc.conTableView.tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 1, 1)];

            }
            [vc.conTableView reloadData];
            [vc.conTableView headerEndRefreshing];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            kDebug(@"Error: %@", error);
            [[iToast makeText:kLocal(@"netError")] show];
            [vc.conTableView headerEndRefreshing];
        }];
        
    }];
    [self.view addSubview:_conTableView];
    [_conTableView headerBeginRefreshing];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Func

-(void)btnClick:(UIButton *)btn
{
    if (btn.tag== 2) {
        MonitorEditVC *editVC = [[MonitorEditVC alloc]initWithData:nil isAdd:YES];
        editVC.block = ^(){
            [_conTableView headerBeginRefreshing];
        };
//        [self.navigationController pushViewController:editVC animated:YES];
        [self.navigationController presentViewController:editVC animated:YES completion:nil];
    }else if(btn.tag == 3){
        MonitorInfoVC *infoVC = [[MonitorInfoVC alloc] init];
//        [self.navigationController pushViewController:infoVC animated:YES];
        [self.navigationController presentViewController:infoVC animated:YES completion:nil];

    }
}

#pragma mark - UITableViewDelegate && UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _dataArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ID =@"cellId";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if(cell == nil){
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
    }
    NSDictionary *dic = _dataArr[indexPath.section];
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:dic[@"mem_headpic"]] placeholderImage:[UIImage imageNamed:@"user"]];
//    cell.imageView.layer.masksToBounds = YES;
//    [cell.imageView.layer setCornerRadius:CGRectGetHeight(cell.imageView.bounds) / 2];
////    cell.imageView.frame = CGRectMake(0, 0, 50, 50);
    cell.textLabel.text = dic[@"mem_name"];
    NSDictionary *stateDic = dic[@"data"];
    NSString *stateStr;
    switch ([stateDic[@"status"] intValue]) {
        case 0:
            stateStr =@"";
            break;
        case 1:
            stateStr =kLocal(@"tem_normal");
            break;
        case 2:
            stateStr =kLocal(@"tem_normal");
            break;
        case 9:
            stateStr =kLocal(@"brownout_log");
            break;
        case 99:
            stateStr =kLocal(@"device_disconnect");
            break;
        default:
            break;
    }
    stateStr = [NSString stringWithFormat:@"%@ %@ %@",stateStr,stateDic[@"xuetang"],stateDic[@"time"]];
    cell.detailTextLabel.text = stateStr;
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{

    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 4;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kLocal(@"editing");
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        NSDictionary *dic = _dataArr[indexPath.section];
        MonitorEditVC *mo = [[MonitorEditVC alloc]initWithData:dic isAdd:NO];
        mo.block = ^(){
            [_conTableView headerBeginRefreshing];
        };
        [self.navigationController pushViewController:mo animated:YES];
    }
}


@end
